package com.sgcc.controller;

import com.sgcc.dao.UserDao;
import com.sgcc.po.User;
import com.sgcc.service.ILoginService;
import com.sgcc.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class LoginServlet {

    @Autowired
    User user;

    @Autowired
    LoginService loginS;

//    @Autowired
//    ApplicationContext applicationContext;

    @Autowired
    UserDao userDao;

    @Autowired
    ILoginService loginService;

    @RequestMapping("/login")
    public String login(HttpServletRequest request) throws Exception {
        /*
         *
         * 先获取用户输入的内容（request对象）
         * 判断用户名和密码是否都是admin，如果不是，重定向到登陆界面，如果是，则登陆成功
         */

        String username = request.getParameter("username");
        String password=request.getParameter("password");
        user.setUsername(username);
        user.setPassword(password);
        User u = loginS.login(user);

        if(u != null){
            /*  	 设置response缓冲编码
             * 		response.setCharacterEncoding("UTF-8");
             *  * 设置浏览器打开文件所采用的编码
             *  	response.setHeader("Content-Type", "text/html;charset=UTF-8");
             *  * 简写方式
             *  	response.setContentType("text/html;charset=UTF-8");
             *  */
            request.setAttribute("user", u);
            return "success";

        }else{

			/*重定向
			response.setStatus(302);
			response.setHeader("location", "/day10/html/login.html");
			//response对象提供了一个方法，可以完成重定向。
			response.sendRedirect("/day10/response/login.html");*/
            //转发
            request.setAttribute("msg", "用户名或密码错误！！！");

            return "login";

//            request.getRequestDispatcher("/jsp/login.jsp").forward(request, response);
        }
    }

    @RequestMapping("/start")
    public String start(HttpServletRequest request) {

        String username = request.getParameter("username");

        /*ILoginService l = (ILoginService)applicationContext.getBean("loginService");

        String sy = l.sayHello(username);*/

        String sy = loginService.sayHello(username);
        System.out.println("...");

        request.setAttribute("msg", sy+" !!!");

        return "Hello";

    }

    @RequestMapping("/listAll")
    public ModelAndView listAll(HttpServletRequest request)throws Exception{

        List<User> userList = userDao.listAll();

//        request.setAttribute("userList",userList);

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("userList", userList);
        // 指定逻辑视图名
        modelAndView.setViewName("userList");
        System.out.println(userList);
        return modelAndView;



    }
}
